import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wanAndroid/bean/user_info_model.dart';
import 'package:wanAndroid/common/http/http_service.dart';
import 'package:wanAndroid/common/http/http_uts.dart';
import 'package:wanAndroid/common/uts/log_uts.dart';
import 'package:wanAndroid/common/uts/sp_uts.dart';
import 'package:wanAndroid/common/uts/toast_uts.dart';
import 'package:wanAndroid/common/uts/ui_uts.dart';
import 'package:wanAndroid/config/AppConfig.dart';
import 'package:wanAndroid/page/page_register.dart';
import 'package:wanAndroid/res/colors.dart';

class PageLogin extends StatefulWidget {
  //启动
  static Future<bool> start(BuildContext context,
      {Map<String, dynamic> args}) async {
    return await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PageLogin(),
        ));
  }

  ///关闭当前页面
  static Future<bool> startAndRemove(BuildContext context) async {
    return await Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(
        builder: (context) => PageLogin(),
        fullscreenDialog: true,
      ),
      (r) => false,
    );
  }

  @override
  State<StatefulWidget> createState() => _PageLogin();
}

class _PageLogin extends State<PageLogin> {
  /// 用户
  String _username = "";

  ///密码
  String _password = "";

  ///记住密码
  bool _isRemember = true;

  ///加载
  bool isLoading = true;

  ///

  /// 控制器
  TextEditingController unameController = TextEditingController();

  TextEditingController pwordController = TextEditingController();

  @override
  void initState() {
    initData();
    super.initState();
  }

  //初始化数据
  void initData() async {
    _username = await SPUts.getString(AppConfig.KEY_USER_NAME, "");
    _password = await SPUts.getString(AppConfig.KEY_PASS_WORD, "");
    LogUts.showLog("_username = $_username");
    LogUts.showLog("_password = $_password");
    if (_username.isNotEmpty && _password.isNotEmpty) {
      unameController = TextEditingController(text: _username);
      pwordController = TextEditingController(text: _password);
      setState(() {
        isLoading = true;
      });
      login();
    } else {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          leading: InkWell(
            onTap: () {
              Navigator.pop(context, false);
            },
            child: const Icon(
              Icons.arrow_back,
              color: Colors.white,
            ),
          ),
          title: UiUts.getTitle("登\t\t录"),
          centerTitle: true,
        ),
        body: Stack(
          children: [
            ///  登录页面操作
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.max,
                children: [
                  /// 用户名
                  Container(
                    margin: const EdgeInsets.only(
                      left: 15,
                      right: 15,
                      top: 50,
                    ),
                    child: TextField(
                      controller: unameController,
                      onChanged: (v) {
                        setState(() {
                          _username = v;
                        });
                      },
                      minLines: 1,
                      decoration: InputDecoration(
                        labelText: "账号",
                        hintText: "请输入账号",
                        hintStyle: TextStyle(
                          color: Color(0xff999999),
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),

                  /// 密码
                  Container(
                    margin: const EdgeInsets.only(
                      left: 15,
                      right: 15,
                      top: 10,
                    ),
                    child: TextField(
                      controller: pwordController,
                      onChanged: (v) {
                        setState(() {
                          _password = v;
                        });
                      },
                      obscureText: true,
                      maxLines: 1,
                      decoration: InputDecoration(
                        labelText: "密码",
                        hintText: "请输入密码",
                        hintStyle: TextStyle(
                          color: Color(0xff999999),
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
                  UiUts.getDivider(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Checkbox(
                        onChanged: (v) {
                          setState(() {
                            _isRemember = v;
                          });
                        },
                        value: _isRemember,
                      ),
                      UiUts.getText(
                        "记住密码",
                        color: ResColors.primaryColor,
                        fontSize: 14,
                      ),
                    ],
                  ),

                  UiUts.getDivider(height: 10),

                  ///登录
                  Container(
                    constraints: BoxConstraints(
                      maxHeight: 50,
                    ),
                    margin: const EdgeInsets.symmetric(
                      horizontal: 15,
                      vertical: 10,
                    ),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(colors: <Color>[
                        Colors.blue.shade300,
                        Colors.blue.shade500,
                        Colors.blue.shade700
                      ]),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: TextButton(
                      onPressed: isLoading
                          ? null
                          : () {
                              if (_username.length > 0 &&
                                  _password.length > 0) {
                                login();
                              } else {
                                ToastUts.showToast(context, text: "请正确填写账号&密码");
                              }
                            },
                      child: isLoading
                          ? UiUts.getText(
                              "正在登录，请稍等···",
                              color: Colors.white,
                              fontSize: 18,
                            )
                          : UiUts.getText(
                              "登\t\t录",
                              color: Colors.white,
                              fontSize: 17,
                            ),
                    ),
                  ),
                ],
              ),
            ),

            ///注册按钮
            Positioned(
              bottom: 50,
              left: 0,
              right: 0,
              child: TextButton(
                child: UiUts.getText(
                  "没账号？去注册",
                  color: ResColors.primaryColor,
                  fontSize: 14,
                ),
                onPressed: () {
                  PageRegister.startAndRemove(context);
                },
              ),
            ),
          ],
        ),
      );

  /// 登录
  Future<void> login() async {
    HttpService.login(
        _username,
        _password,
        HttpCallback((resp) {
          UserInfoModel data = UserInfoModel.fromJson(resp.data);
          if (0 == data.errorCode) {
            if (_isRemember) {
              SPUts.setString(AppConfig.KEY_USER_NAME, _username);
              SPUts.setString(AppConfig.KEY_PASS_WORD, _password);
              SPUts.setBoolean(AppConfig.KEY_IS_LOGIN, true);
            }
            Navigator.pop(context, true);
          } else {
            SPUts.setBoolean(AppConfig.KEY_IS_LOGIN, false);
            ToastUts.showToast(context, text: data.errorMsg);
          }

          setState(() {
            isLoading = false;
          });
        }, (e) {
          SPUts.setBoolean(AppConfig.KEY_IS_LOGIN, false);
          ToastUts.showToast(context, text: e.toString());

          setState(() {
            isLoading = false;
          });
        }));
  }
}
